package cn.edu.njust.control;

import cn.edu.njust.mapper.UserMapper;
import cn.edu.njust.pojo.Register;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;

@WebServlet(name = "removeServlet", value = "/removeServlet")
public class RemoveRegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //调用mapper根据用户ID查询对像
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        HttpSession session = request.getSession();

        Register reg =  (Register) session.getAttribute("registerUser");
        //撤销用户
        userMapper.remove(reg);
        userMapper.remove01(reg.getIdNo());
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
        //完事后跳走
        response.sendRedirect("preRegister.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
